import { getLocales } from 'expo-localization';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 支持的语言类型
export type SupportedLanguage = 'zh' | 'en';

// 语言配置
export const SUPPORTED_LANGUAGES: Record<SupportedLanguage, { name: string; nativeName: string }> = {
  zh: { name: 'Chinese', nativeName: '中文' },
  en: { name: 'English', nativeName: 'English' }
};

// 语言文件
const translations: Record<SupportedLanguage, any> = {
  zh: require('../../locales/zh.json'),
  en: require('../../locales/en.json')
};

// 存储键
const LANGUAGE_STORAGE_KEY = '@app_language';

class I18nManager {
  private currentLanguage: SupportedLanguage = 'zh';
  private listeners: Array<(language: SupportedLanguage) => void> = [];

  constructor() {
    this.initializeLanguage();
  }

  private async initializeLanguage() {
    try {
      // 尝试从存储中获取用户设置的语言
      const storedLanguage = await AsyncStorage.getItem(LANGUAGE_STORAGE_KEY);
      
      if (storedLanguage && this.isValidLanguage(storedLanguage)) {
        this.currentLanguage = storedLanguage as SupportedLanguage;
      } else {
        // 如果没有存储的语言，使用系统语言
        const systemLocales = getLocales();
        const systemLanguage = systemLocales[0]?.languageCode;
        
        if (systemLanguage && this.isValidLanguage(systemLanguage)) {
          this.currentLanguage = systemLanguage as SupportedLanguage;
        }
      }
    } catch (error) {
      console.warn('Failed to initialize language:', error);
    }
  }

  private isValidLanguage(language: string): boolean {
    return Object.keys(SUPPORTED_LANGUAGES).includes(language);
  }

  getCurrentLanguage(): SupportedLanguage {
    return this.currentLanguage;
  }

  async setLanguage(language: SupportedLanguage) {
    if (!this.isValidLanguage(language)) {
      throw new Error(`Unsupported language: ${language}`);
    }

    this.currentLanguage = language;
    
    try {
      await AsyncStorage.setItem(LANGUAGE_STORAGE_KEY, language);
    } catch (error) {
      console.warn('Failed to save language preference:', error);
    }

    // 通知所有监听器
    this.listeners.forEach(listener => listener(language));
  }

  translate(key: string, params?: Record<string, string | number>): string {
    const keys = key.split('.');
    let value = translations[this.currentLanguage];

    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        // 如果当前语言没有找到，尝试使用中文作为后备
        if (this.currentLanguage !== 'zh') {
          let fallbackValue = translations.zh;
          for (const fallbackKey of keys) {
            if (fallbackValue && typeof fallbackValue === 'object' && fallbackKey in fallbackValue) {
              fallbackValue = fallbackValue[fallbackKey];
            } else {
              return key; // 如果后备语言也没有，返回key本身
            }
          }
          value = fallbackValue;
        } else {
          return key; // 返回key本身作为后备
        }
        break;
      }
    }

    if (typeof value !== 'string') {
      return key;
    }

    // 处理参数替换
    if (params) {
      return Object.entries(params).reduce((text, [param, replacement]) => {
        return text.replace(new RegExp(`{{${param}}}`, 'g'), String(replacement));
      }, value);
    }

    return value;
  }

  // 添加语言变化监听器
  addLanguageChangeListener(listener: (language: SupportedLanguage) => void) {
    this.listeners.push(listener);
    return () => {
      const index = this.listeners.indexOf(listener);
      if (index > -1) {
        this.listeners.splice(index, 1);
      }
    };
  }

  // 获取所有支持的语言
  getSupportedLanguages() {
    return SUPPORTED_LANGUAGES;
  }
}

// 创建单例实例
export const i18n = new I18nManager();

// 便捷的翻译函数
export const t = (key: string, params?: Record<string, string | number>) => {
  return i18n.translate(key, params);
};